package pay.redis.impl;

import cn.hutool.core.util.StrUtil;
import org.redisson.Redisson;
import org.redisson.RedissonMultiLock;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.stereotype.Service;
import pay.redis.RLockService;
import pay.redis.config.RedissonConfig;

import javax.annotation.Resource;

@Service
public class RLockServiceImpl implements RLockService {

	@Resource
	private RedissonConfig redissonConfig;

	private static RedissonClient redissonClient;

	/**
	 * 初始化RedissonClient。
	 */
	private RedissonClient getClient() {
		if (redissonClient == null) {
			Config config = new Config();
			// 单机模式
			SingleServerConfig serverConfig = config.useSingleServer();
			serverConfig.setAddress(
					StrUtil.builder("redis://", redissonConfig.getHost(), ":", redissonConfig.getPort()).toString());
			serverConfig.setConnectionPoolSize(redissonConfig.getConnectionPoolSize());
			serverConfig.setConnectionMinimumIdleSize(redissonConfig.getConnectionMinimumIdleSize());
			serverConfig.setDatabase(1);
			if (StrUtil.isNotEmpty(redissonConfig.getPassword())) {
				serverConfig.setPassword(redissonConfig.getPassword());
			}
			redissonClient = Redisson.create(config);
		}
		return redissonClient;
	}

	@Override
	public RLock getLock(String lockKey) {
		return this.getClient().getLock(lockKey);
	}

	@Override
	public RLock getFairLock(String lockKey) {
		return this.getClient().getFairLock(lockKey);
	}

	@Override
	public RedissonMultiLock getMultiLock(RLock... locks) {
		return new RedissonMultiLock(locks);
	}

	@Override
	public RedissonRedLock getRedLock(RLock... locks) {
		return new RedissonRedLock(locks);
	}

	@Override
	public RReadWriteLock getReadWriteLock(String lockKey) {
		return this.getClient().getReadWriteLock(lockKey);
	}

}
